package dao.advert;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import pojo.advert.TblAdvert;

import comment.HibernateSessionFactory;

import vo.advert.AdvertVo;

public class AdvertDao {
	public TblAdvert uptTblAdvert(AdvertVo advertVo){
		TblAdvert tblAdvert = new TblAdvert();
		try{
			Session session = HibernateSessionFactory.getSession();
			tblAdvert = (TblAdvert) session.get(TblAdvert.class, advertVo.getId());
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return tblAdvert;
		
	}
	public void deleteTblAdver(String ids){
		Transaction tc = null;
		String hql = "delete from TblAdver where avertType in ("+ids+")";
		try{
			Session session = HibernateSessionFactory.getSession();
			tc = session.beginTransaction();
			Query hqlQuery = session.createQuery(hql);
			hqlQuery.executeUpdate();
			tc.commit();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public List<AdvertVo> getTblAdvert(AdvertVo advertVo){
		List<AdvertVo> advertVoList = new ArrayList();
		String hql = "select new vo.advert.AdvertVo(ta.id,ta.advertAddressId,taa.advertName,ta.advertName,"
			+"ta.notes,tdf.value,ta.advertPath) from TblAdvertAddress taa, TblAdvert ta,Tbldeftype tdf where taa.id=ta.advertAddressId and ta.avertType=tdf.code";
		Session session = HibernateSessionFactory.getSession();
		if(advertVo.getAdvertName()!=null&&!advertVo.getAdvertName().isEmpty()){
			hql = hql + " and ta.advertName like '%"+advertVo.getAdvertName()+"%'";
		}
		hql = hql + " and ta.avertType='"+advertVo.getAvertType()+"'";
		try{
			Query hqlQuery = session.createQuery(hql);
			hqlQuery.setFirstResult((advertVo.getCurPage()-1)*advertVo.getSizePerPage());
			hqlQuery.setMaxResults(advertVo.getSizePerPage());
			advertVoList = hqlQuery.list();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return advertVoList;
		
	}
	public int getTblAdvertCount(AdvertVo advertVo){
		int result = 0;
		String hql = "select count(*) from TblAdvertAddress taa, TblAdvert ta,Tbldeftype tdf where taa.id=ta.advertAddressId and ta.avertType=tdf.code";
		Session session = HibernateSessionFactory.getSession();
		if(advertVo.getAdvertName()!=null&&!advertVo.getAdvertName().isEmpty()){
			hql = hql + " and ta.advertName like '%"+advertVo.getAdvertName()+"%'";
		}
		hql = hql + " and ta.avertType='"+advertVo.getAvertType()+"'";
		try{
			Query hqlQuery = session.createQuery(hql);
			List countList = hqlQuery.list();
		    result = ((Long)countList.get(0)).intValue();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return result;
		
	}

}
